package org.mjl.jackson.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AmapUtil
 *
 * @author mjl
 * @date 2021-04-14
 */
public class AmapUtil {
    public static final String CODE = "38eadf03e962cf1a4bdbdd82a7125416";

    /**
     * 输入地址返回经纬度
     * https://lbs.amap.com/api/webservice/guide/api/georegeo#geo
     */
    public static final String AMAP_GEO_API = "https://restapi.amap.com/v3/geocode/geo";

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static Map<String, String> getLonlat(String address) {
        Map<String, String> resultMap = new HashMap<>();

        String url = AMAP_GEO_API + "?output=JSON&key=" + CODE + "&address=" + address;
        try {
            RestTemplate restTemplate = new RestTemplate();
            String object = restTemplate.getForObject(url, String.class);
            System.out.println(object);
            Map<String, Object> map = objectMapper.readValue(object, Map.class);
            String status = (String) map.get("status");
            if ("1".equals(status)) {
                List<Map<String, Object>> geocodes = (List<Map<String, Object>>) map.get("geocodes");
                if (!CollectionUtils.isEmpty(geocodes)) {
                    Map<String, Object> geocode = geocodes.get(0);
                    String location = String.valueOf(geocode.get("location"));
                    String[] split = location.split(",");
                    resultMap.put("lon", split[0]);
                    resultMap.put("lat", split[1]);
                    resultMap.put("lonlat", location);
                }
            }
            resultMap.put("msg", String.valueOf(map.get("info")));
            return resultMap;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(getLonlat("甘肃省兰州市天庆嘉园"));
    }
}
